package com.orhon.smartcampus.modules.systemctl.fetcher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.systemctl.dao.OperationApiDao;
import com.orhon.smartcampus.modules.systemctl.entity.OperationApi;
import com.orhon.smartcampus.modules.systemctl.gqlModel.GQLOperationApi;
import com.orhon.smartcampus.modules.systemctl.mm.OperationApiMapper;
import com.orhon.smartcampus.utils.ObjectToMap;
import com.orhon.smartcampus.utils.Util;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class OperationApisFetcher implements DataFetcher {
	@Autowired
	OperationApiDao operationApiDao;

	@Override
	public Object get(DataFetchingEnvironment environment) throws Exception {

		List<GQLOperationApi> gqlOperationApi = new ArrayList<>();

		GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(environment);
		String hql = "from OperationApi where 1=1 ";

		if (environment.containsArgument("condition")) {
			HashMap<String, Object> map = ObjectToMap.to(environment.getArgument("condition"));
			if (map.get("id") != null) {
				hql += "and id = " + map.get("id");
			}
			if (map.get("api_id") != null) {
				hql += "and api_id " + Util.decide(map.get("api_id"));
			}

			if (map.get("operation_id") != null) {
				hql += "and operation_id " + Util.decide(map.get("operation_id"));
			}

			if (map.get("userId") != null) {
				hql += " and operation_id in (select systemctlOperationsByOperationId from OperationUserRelation where userUsersByUserId =" +map.get("userId")+ ")";
			}

		}
		List<OperationApi> list = operationApiDao.find(hql, null, page.getPage(), page.getLimit());
		for (OperationApi item : list) {
			GQLOperationApi operationApi = OperationApiMapper.MAPPER.toOperationApi(item);
			gqlOperationApi.add(operationApi);
		}

		Long total = 0L;
		if (environment.getSelectionSet().contains("total")) {
			total = operationApiDao.getTotalCount(hql);
		}
		return Result.ok().put("data", gqlOperationApi).put("total", total);
	}
}
